/*
 * @Author: miteng 973203639@qq.com
 * @Date: 2024-06-20 10:35:52
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-06-23 16:28:57
 * @Description:
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved.
 */
import router from '@/router';
import { RouteRecordRaw } from 'vue-router';
import { useUserStoreHook } from '@/framework/store/modules/user';
import { usePermissionStoreHook } from '@/framework/store/modules/permission';
import { useSettingsStore } from '@/framework/store/modules/settings';
import getPageTitle from '@/framework/utils/get-page-title';

import { setToken } from '@/framework/utils/auth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();
const settingsStore = useSettingsStore();

// 白名单路由
const whiteList = [
  '/test',
  '/forgetPw',
  '/updatePassword',
  '/auth',
  '/',
  '/project',
  '/univer-sheet',
  '/ag-grid'
];
const licenseResp = ref();
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStoreHook();
  const queryToken = to.query.token;
  if (queryToken) {
    setToken(queryToken as string);
    userStore.setUserToken(queryToken as string);
    delete to.query.token;
    // setTimeout(() => {
    //   next();
    // }, 200);
  }
  document.title = getPageTitle(to.meta.title as string);
  if (userStore.token) {
    // 登录成功，跳转到首页
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasGetUserInfo = userStore.roles.length > 0;
      if (hasGetUserInfo) {
        if (to.path !== '/auth') {
          licenseResp.value = await userStore.getLicense();
          console.log('licenseResp111111111111111111', licenseResp.value);
        }
        if (!licenseResp.value && to.path !== '/auth') {
          next('/auth');
        }
        if (to.matched.length === 0) {
          // from.name ? next({ name: from.name }) : next('/401');
          if (to.path === '/' && permissionStore.firstPath) {
            next({ path: permissionStore.firstPath });
          } else {
            from.name
              ? next({ name: from.name })
              : next({
                  path: permissionStore.firstPath || '/401',
                  replace: true
                });
          }
        } else {
          next();
        }
      } else {
        try {
          let roles: string[] = [];
          // @ts-expect-error微前端环境下
          if (window.rawWindow?.__MICRO_APP_BASE_APPLICATION__) {
            // @ts-expect-error
            let micoUserInfo =
              window.rawWindow.eventCenterForAppNameVite.getData();
            if (micoUserInfo && micoUserInfo.userInfo) {
              // 主动获取基座下发的数据;可在此处获取用户信息
              userStore.microappUserInfo(micoUserInfo.userInfo);
              roles = userStore.roles;
            }
          } else {
            settingsStore.getCurrentThemeInfo(); // 获取统一导航主题
            settingsStore.getServers(); //获取服务状态（消息服务是否启动，统一导航是否显示小铃铛）
            await settingsStore.getBasicLoginAdress(); // 统一登录地址
            roles = (await userStore.getInfo()).roles; // 获取用户信息
          }
          settingsStore.getAppName();

          const accessRoutes: RouteRecordRaw[] =
            await permissionStore.generateRoutes(roles);
          console.log('accessRoutes1', accessRoutes);

          accessRoutes.forEach(route => {
            router.addRoute(route);
          });
          console.log('router', router);

          if (accessRoutes.length) {
            // to 如果是'/'路由的话,就跳转第一个导航路由firstPath(firstPath不存在，则证明该用户下没有菜单路由，直接条状401)，否则 ...to
            if (to.path === '/' || to.path === '/401') {
              next({ path: permissionStore.firstPath, replace: true });
            } else {
              next({ ...to, replace: true });
            }
          } else {
            // 动态路由为空时，直接跳转401
            next({ path: '/401', replace: true });
          }
        } catch (error) {
          // 移除 token 并跳转登录页
          await userStore.resetToken();
          resetLogin(true);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      resetLogin();
      // next(`/login?authMode=1&ssoLoginFlag=true&tenantId=000000&redirect=${to.path}`);
      NProgress.done();
    }
  }
});
async function resetLogin(flag?: boolean): Promise<void> {
  // if(!localStorage.getItem('basicLoginAddress')) {
  // 查找统一登录地址
  await settingsStore.getBasicLoginAdress();
  // }
  // location.href = `http://localhost:3000/login?redirect=${location.origin}` // 本地测试
  location.href = `${
    localStorage.getItem('basicLoginAddress') || ''
  }/login?redirect=${location.origin}${flag ? '&isLogout=true' : ''}`;
}
router.afterEach(() => {
  NProgress.done();
});
